/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Linq;

#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

namespace Oceanside
{
    public class Logging
    {
        const string CONST_LOGNAME = "Oceanside";

        /// <summary>
        /// 
        /// </summary>
        private static EventLog _eventLog = null;

        /// <summary>
        /// Make sure the debugging log directory exists.
        /// </summary>
        public static void Init(string source)
        {
            try
            {
                // Create the source, if it does not already exist.
                if (!EventLog.SourceExists(source, Environment.MachineName))
                {
                    //An event log source should not be created and immediately used.
                    //There is a latency time to enable the source, it should be created
                    //prior to executing the application that uses the source.
                    EventLog.CreateEventSource(source, CONST_LOGNAME);
                }

                // Create an EventLog instance and assign its source.
                _eventLog = new EventLog();
                _eventLog.Source = source;

            }
            catch
            {

            }
        }

        public static void ClearEventLog()
        {
            try
            {
                if (_eventLog != null)
                {
                    _eventLog.Clear();
                }
            }
            catch { }
        }

        public static void DumpLogToFile()
        {
            try
            {
                if (_eventLog != null && _eventLog.Entries != null && _eventLog.Entries.Count != 0)
                {
                    string storeId = SHIFT.GlobalContext.SYSCONFIGS.FirstOrDefault().StoreId.ToString();
                    string wanIp = NetUtils.GetWanIpAddress();
                    string hostName = NetUtils.GetHostName();
                    NetUtils.IPLocator loc;
                    string fileName = "C:\\log" + "-" + wanIp + "--" + hostName + ".txt";
                    using (FileStream outfile = File.Open(fileName, FileMode.Create))
                    {
                        using (StreamWriter sw = new StreamWriter(outfile))
                        {
                            int index = 1;

                            loc = NetUtils.IPDetails.GetIpInformation(wanIp);
                            sw.WriteLine("Machine Name: " + hostName);
                            sw.WriteLine("Remote IP   : " + wanIp);
                            sw.WriteLine("Country     : " + loc.Country);
                            sw.WriteLine("City        : " + loc.City);
                            sw.WriteLine("State       : " + loc.State);
                            sw.WriteLine("Zipcode     : " + loc.Zip);
                            sw.WriteLine("Hostname    : " + loc.HostName);

                            sw.WriteLine("-------------");
                            foreach (EventLogEntry entry in _eventLog.Entries)
                            {
                                sw.WriteLine(Constants.NEWLINE + "Entry   : " + index++.ToString("D6"));
                                sw.WriteLine("Time    : " + 
                                    entry.TimeGenerated.ToShortDateString() + " " + entry.TimeGenerated.ToShortTimeString());
                                sw.WriteLine("Message : " + entry.Message + Constants.NEWLINE);

                            }
                        }
                    }
                    NetUtils.SendEmail("support@oceansidesw.com", storeId, "Customer Log File", fileName);
                    File.Delete(fileName);
                    _eventLog.Clear();
                }
            }
            catch { }
        }


        private static int _errorCounter = 0;
        private static object _countLock = new object();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="osideType"></param>
        /// <param name="e"></param>
        /// <param name="eLogtype"></param>
        public static void LogException(Error.EType osideType, Exception e, EventLogEntryType eLogtype = EventLogEntryType.Information)
        {
            try
            {
                string unWoundMessage = "";
                if (_eventLog != null)
                {
                    if (e != null)
                    {
                        CreateString(ref unWoundMessage, e);
                    }
                    string prefeix = "Oceanside Message Type: " + osideType.ToString() + Environment.NewLine + Environment.NewLine;

                    lock (_countLock)
                    {
                        _eventLog.WriteEntry(prefeix + unWoundMessage, eLogtype, ++_errorCounter);
                    }
                }
            }
            catch
            {
                ///Logging an exception here could cause another exception.
                /*Logging.LogMessage(exc.ToString());*/
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        public static void LogException(Exception e)
        {
            try
            {
                string unWoundMessage = "";
                if (_eventLog != null && e != null)
                {
                    CreateString(ref unWoundMessage, e);

                    lock (_countLock)
                    {
                        _eventLog.WriteEntry(unWoundMessage, EventLogEntryType.Information, ++_errorCounter);
                    }
                }

            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="output"></param>
        /// <param name="e"></param>
        private static void CreateString(ref string output, Exception e)
        {
            string unWoundMessage = "";
            if (e != null)
            {
                ///Get the Outer Exception Information.
                string stack = e.StackTrace;
                string source = e.Source;
                string target = e.TargetSite == null ? "" : e.ToString();
                string message = e.Message;
                string eType = e.GetType() == null ? "" : e.GetType().ToString();

                FormatExceptionInfo(ref unWoundMessage, "**Outer Exception**", source, target, eType, stack, message);

                ///Get the base exception Information.
                Exception baseException = e.GetBaseException();
                if (baseException != null)
                {
                    string baseStack = baseException.StackTrace;
                    string baseSource = baseException.Source;
                    string baseTarget = baseException.TargetSite == null ? "" : baseException.TargetSite.ToString();
                    string baseMessage = baseException.Message;
                    string baseType = baseException.GetType() == null ? "" : baseException.GetType().ToString();
                    FormatExceptionInfo(ref unWoundMessage, "**Base Exception**", baseSource, baseTarget, baseType, baseStack, baseMessage);
                }

                Exception inner = e.InnerException;
                int count = 1;
                while (inner != null)
                {
                    string innerStack = inner.StackTrace;
                    string innerSource = inner.Source;
                    string innerTarget = inner.TargetSite == null ? "" : inner.TargetSite.ToString();
                    string innerMessage = inner.Message == null ? "" : inner.Message;
                    string innerType = inner.GetType() == null ? "" : inner.GetType().ToString();
                    FormatExceptionInfo(ref unWoundMessage, "**Inner Exception " + count++ + "**", innerSource, innerTarget, innerType, innerStack, innerMessage);

                    ///See if there is another inner exception.
                    inner = inner.InnerException;
                }
            }
            output = unWoundMessage;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="outStr"></param>
        /// <param name="stack"></param>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <param name="message"></param>
        /// <param name="eType"></param>
        private static void FormatExceptionInfo(ref string outStr, string title, string source, string target, string eType, string stack, string message)
        {
            if (outStr == null)
            {
                outStr = "";
            }

            outStr += "TITLE: " + Constants.NEWLINE;
            outStr += Constants.SPACES + title + Constants.NEWLINE;

            outStr += "SOURCE: " + Constants.NEWLINE;
            outStr += Constants.SPACES + source + Constants.NEWLINE;

            outStr += "TARGET: " + Constants.NEWLINE;
            outStr += Constants.SPACES + target + Constants.NEWLINE;

            outStr += "TYPE: " + Constants.NEWLINE;
            outStr += Constants.SPACES + eType + Constants.NEWLINE;

            outStr += "STACK: " + Constants.NEWLINE;
            outStr += Constants.SPACES + stack + Constants.NEWLINE;

            outStr += "MESSAGE: " + Constants.NEWLINE;
            outStr += Constants.SPACES + message + Constants.NEWLINE;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        public static void LogMessage(String mesg)
        {
            try
            {
                if (_eventLog != null)
                {
                    lock (_countLock)
                    {
                        _eventLog.WriteEntry(mesg, EventLogEntryType.Information, ++_errorCounter);
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        public static void LogRetry(System.Reflection.MethodBase methBase)
        {
            try
            {
                if (_eventLog != null)
                {
                    lock (_countLock)
                    {
                        _eventLog.WriteEntry("Database Retry: " + methBase.DeclaringType + "." + methBase.Name,
                            EventLogEntryType.Error, ++_errorCounter);
                    }
                }
            }
            catch { }
        }
    }
}
